<template>
	<view class="order-list" :class="themeName">
		<!-- Tabs -->
		<navbar title="订单列表"></navbar>
		<u-tabs :list="tabsList" :is-scroll="false" :height="80" :active-color="themeColor" :bar-style="{ top: '100%' }"
			:current="tabsIndex" @change="changeCurrentTab" />

		<block v-if="currentTab.sign=='all'">
			<view class="query-line flex row-between">
				<view class="title">{{$zhTran('时间筛选')}}</view>
				<view class="flex" @click="chooseTime">
					<text>{{time.desc}}</text>
					<u-icon name="arrow-down" size="24" class="m-l-10" color="rgba(196, 196, 196, 1)"></u-icon>
				</view>
			</view>

			<view class="query-line flex row-between" v-if="time.value == 'diy'">
				<view class="date" @click="showTimeVisible=true">{{timeRange.start_desc}}</view>
				<view class="line"></view>
				<view class="date" @click="showTimeVisible=true">{{timeRange.end_desc}}</view>
			</view>
		</block>

		<!-- Order Lists -->
		<view class="order-item">
			<view class="order-item-box">
				<mescroll-uni ref="mescrollRef" :fixed="false" :up="{
				auto: false,
				noMoreSize: 3,
				empty: {
					icon: $getImageUri('resource/image/shopapi/uniapp/empty/order.png'),
					tip: $zhTran('暂无订单~'),
					fixed: true
				}
			}" :bottom="0" :down="{ auto: false }" @init="mescrollInit" @down="downCallback" @up="upCallback">
					<block v-for="(tabItem, tabIndex) in tabsList" :key="tabItem['sign']">
						<view class="order-contain" v-if="currentTab['sign'] === tabItem['sign']">
							<view class="order" v-for="orderItem in tabsList[tabIndex].list" :key="orderItem.id">
								<!-- Order Header -->
								<view class="order-header p-t-10" :style="{height:'100rpx'}">

									<view class="flex">
										<!-- S 订单Tag -->
										<block v-if="orderItem.delivery_type === 2">
											<view class="order-tag order-tag--green">{{$zhTran('自提')}}</view>
										</block>
										<block v-if="orderItem.pay_way === 8">
											<view class="order-tag order-tag--red">{{$zhTran('货到付款')}}</view>
										</block>
										<block v-if="[1, 2, 3].includes(orderItem.order_type)">
											<view :class="[
										'order-tag',
										`order-tag--${orderType[orderItem.order_type]['style']}`
									]">{{ orderType[orderItem.order_type]['name'] }}</view>
										</block>
										<!-- E 订单Tag -->

										<view class="order-sn">{{$zhTran('订单编号:')}}{{ orderItem.sn }}</view>
										<block v-if="orderItem.delivery_type === 1 || orderItem.delivery_type === 4">
											<view :class="[
										'order-status',
										`order-status--${orderStatus[orderItem.order_status]['style']}`
									]">{{ orderStatus[orderItem.order_status]['name'] }} </view>
										</block>
										<block v-else-if="orderItem.delivery_type === 2">
											<view :class="[
										'order-status',
										`order-status--${orderSelffetchStatus[orderItem.order_status]['style']}`
									]">{{ orderSelffetchStatus[orderItem.order_status]['name'] }}</view>
										</block>
									</view>
									<view>{{$zhTran('车牌号：')}}{{orderItem.address.car_num||''}}</view>
								</view>

								<!-- Order Main -->
								<view class="order-main" @tap="goOrderDetail(orderItem.id)">
									<goods-card v-for="(goodsItem, goodsIndex) in orderItem.order_goods"
										:key="goodsIndex" shape="rectangle" :name="goodsItem.goods_name"
										:image="goodsItem.goods_image"
										:contain-style="{ 'border-raius': 0, 'height': '330rpx' }"
										:image-style="{ 'width': '180rpx', 'height': '180rpx' }">
										<view class="flex-1" slot="default">
											<view class="xs m-t-10" v-if="order_extend.show_order_list_goods_tag">
												<u-image width="80rpx" height="40rpx" :src="goodsItem.tag_desc"
													v-if="goodsItem.tag_desc != ''" />
											</view>
											<view class="gfa-tag" v-if="goodsItem.is_gifts">{{$zhTran('赠品')}}</view>
											<text class="muted xs m-t-10">{{ goodsItem.spec_value_str }}</text>
											<view class="xs m-t-10" v-if="order_extend.show_order_list_goods_code"
												:style="{
											color: order_extend.order_list_goods_code_color
										}">{{$zhTran('编码：')}}{{ goodsItem.code == null ? '' : goodsItem.code }}</view>
											<view class="xs m-t-10" v-if="order_extend.show_order_list_goods_model"
												:style="{
											color: order_extend.order_list_goods_model_color
										}">{{$zhTran('型号：')}}{{ goodsItem.goods_model == null ? '' : goodsItem.goods_model }}</view>
											<view class="m-t-10 flex row-between">
												<price v-if="orderItem.order_type == 0 || orderItem.order_type == 4"
													:content="goodsItem.original_price" mainSize="32rpx"
													minorSize="24rpx" :prefix="price_symbol" />
												<price v-else :content="goodsItem.goods_price" mainSize="32rpx"
													minorSize="24rpx" :prefix="price_symbol" />
												<text
													class="lighter sm">x{{goodsItem.aux_info!=undefined && Object.keys(goodsItem.aux_info).length > 0? goodsItem.aux_info.goods_num+goodsItem.aux_info.aux_unit_name+'( '+goodsItem.goods_num+ goodsItem.unit_desc+' )':goodsItem.goods_num}}</text>
											</view>
										</view>
									</goods-card>
									<block v-if="orderItem.pay_way == 5">
										<view class="order-desc">
											<text>{{$zhTran('共 '+orderItem.total_num +' 件商品,订单总金额:')}}</text>
											<price class="normal lg" :content="orderItem.order_amount"
												:prefix="price_symbol" />
										</view>
										<view class="order-desc">
											<text>{{$zhTran('余额付款:')}}</text>
											<price class="normal lg" :content="orderItem.bal_amount"
												:prefix="price_symbol" />
										</view>
										<view class="order-desc">
											<text>{{ $zhTran(orderItem.pay_status == 2 ? '应付款:' : '微信付款：') }}</text>
											<price class="normal lg" :content="orderItem.need_amount"
												:prefix="price_symbol" />
										</view>
									</block>
									<block v-else>
										<view class="order-desc" v-if="orderItem.integrate_amount > 0">
											<text>{{$zhTran('共 '+ orderItem.total_num +' 件商品,已付款:')}}</text>
											<price class="normal lg" :content="orderItem.done_amount"
												:prefix="price_symbol" />
											<text>{{$zhTran(',应付款:')}}</text>
											<price class="normal lg" :content="orderItem.integrate_amount"
												:prefix="price_symbol" />
										</view>
										<view class="order-desc" v-else>
											<text>{{$zhTran('共 '+ orderItem.total_num +' 件商品,应付款:')}}</text>
											<price class="normal lg" :content="orderItem.order_amount"
												:prefix="price_symbol" />
										</view>
									</block>
								</view>

								<!-- Order Footer -->
								<view class="order-footer" v-if="orderItem.buttons.length">
									<block v-for="buttonItem in orderItem.buttons" :key="buttonItem.event">
										<view :class="[
										'order-button',
										`order-button--${buttonItem.style}`
									]" @tap="onOrderButtons(buttonItem['event'], orderItem.id,'', order_extend,orderItem.order_goods)">
											{{ buttonItem.name }}</view>
									</block>
									<block v-if="!orderItem.audit_status && orderItem.audit_show">
										<view :class="[
										'order-button', 
										`order-button--primary`
									]">{{ orderItem.audit_status_desc }}</view>
									</block>
								</view>
							</view>
						</view>
					</block>
				</mescroll-uni>
			</view>
			<w-jishuzhichi :class="[{'jishuzhichi-nodata':currentTabList.length == 0}]" />
		</view>
		<u-popup v-model="showVisible" mode="bottom" border-radius="14" :closeable="false"
			:safe-area-inset-bottom="true" @close="closePopup">
			<view class="time-box">
				<view class="time-header">{{$zhTran('时间')}}</view>
				<view class="time-main">
					<view :class="time.value == 'week'?'selected time-sel':' time-sel'" @click="queryTime('week','本周')">
						{{$zhTran('本周')}}
					</view>
					<view :class="time.value == 'month'?'selected time-sel':' time-sel'"
						@click="queryTime('month','本月')">
						{{$zhTran('本月')}}
					</view>
					<view :class="time.value == 'year'?'selected time-sel':' time-sel'" @click="queryTime('year','本年')">
						{{$zhTran('本年')}}
					</view>
					<view :class="time.value == 'diy'?'selected time-sel':' time-sel'" @click="queryTime('diy','自定义')">
						{{$zhTran('自定义')}}
					</view>
				</view>

				<u-gap height="20" bg-color="rgba(246, 247, 249, 1)"></u-gap>
				<view class="time-footer">
					<button hover-class="none" class="btn btn--cancel" size="md"
						@tap="showVisible=false">{{$zhTran('取消')}}</button>
				</view>
			</view>
		</u-popup>
		<u-calendar v-model="showTimeVisible" mode="range" @change="getDateValue"></u-calendar>
	</view>
</template>


<script>
	import {
		apiOrderList
	} from '@/api/order'
	import OrderMixin from '@/mixins/order'
	import {
		PaymentStatusEnum
	} from '@/utils/enum'
	import Cache from '@/utils/cache'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";
	export default {
		name: 'OrderList',
		mixins: [OrderMixin, MescrollMixin],

		data() {
			return {
				// Tabs列表
				tabsList: [{
					sign: 'all',
					name: this.$zhTran('全部'),
					list: [],
				}, {
					sign: 'pay',
					name: this.$zhTran('待付款'),
					list: [],
				}, {
					sign: 'delivery',
					name: this.$zhTran('待发货'),
					list: [],
				}, {
					sign: 'take',
					name: this.$zhTran('待收货'),
					list: [],
				}, {
					sign: 'finish',
					name: this.$zhTran('已完成'),
					list: [],
				}, {
					sign: 'close',
					name: this.$zhTran('已关闭'),
					list: [],
				}],
				tabsIndex: '', // Tabs索引

				// 订单状态
				orderStatus: {
					0: {
						name: this.$zhTran('待付款'),
						style: 'primary',
					},
					1: {
						name: this.$zhTran('待发货'),
						style: 'primary',
					},
					2: {
						name: this.$zhTran('待收货'),
						style: 'primary',
					},
					3: {
						name: this.$zhTran('已完成'),
						style: 'primary',
					},
					4: {
						name: this.$zhTran('已关闭'),
						style: 'muted',
					}
				},

				// 订单状态
				orderSelffetchStatus: {
					0: {
						name: this.$zhTran('待付款'),
						style: 'primary',
					},
					1: {
						name: this.$zhTran('待取货'),
						style: 'primary',
					},
					3: {
						name: this.$zhTran('已完成'),
						style: 'primary',
					},
					4: {
						name: this.$zhTran('已关闭'),
						style: 'muted',
					}
				},

				// 订单类型
				orderType: {
					1: {
						name: this.$zhTran('拼团'),
						style: 'pink'
					},
					2: {
						name: this.$zhTran('秒杀'),
						style: 'red'
					},
					3: {
						name: this.$zhTran('砍价'),
						style: 'blue'
					},
				},
				price_symbol: '￥',
				order_extend: {
					show_order_list_goods_code: 0,
					order_list_goods_code_color: '',
					show_order_list_goods_model: 0,
					order_list_goods_model_color: '',
					show_order_list_goods_tag: 0,
					place_order_again: 0
				},
				time: {
					value: 'month',
					desc: this.$zhTran('本月'),
				},
				timeRange: {
					start: '',
					start_desc: this.$zhTran('开始时间'),
					end: '',
					end_desc: this.$zhTran('结束时间'),
				},
				showVisible: false,
				showTimeVisible: false,
			}
		},

		computed: {
			// 当前Tab项
			currentTab() {
				return this.tabsList[this.tabsIndex] || {}
			},

			currentTabList() {
				if (this.tabsList[this.tabsIndex] == undefined) return []
				return this.tabsList[this.tabsIndex].list || []
			},

			// 映射Tabs项
			mapTabsItem() {
				return sign => this.tabsList.find(item => item['sign'] === sign)
			}
		},

		methods: {
			// 更改当前Tab页
			changeCurrentTab(index) {
				this.tabsIndex = index
				this.refreshOrderData()
			},

			// 刷新订单数据 @Mixins【/src/mixins/order.js】内调用，请勿删除
			refreshOrderData() {
				this.$nextTick(() => {
					this.mescroll.resetUpScroll()
				})
			},
			closePopup() {
				this.showVisible = false
			},
			chooseTime() {
				this.showVisible = true
			},
			queryTime(value, desc) {
				this.time.desc = this.$zhTran(desc)
				this.time.value = value
				if (value != 'diy') {
					this.refreshOrderData()
				}
				this.closePopup()
			},
			getDateValue(e) {
				console.log(e)
				this.timeRange.start = e.startDate
				this.timeRange.start_desc = e.startDate
				this.timeRange.end = e.endDate
				this.timeRange.end_desc = e.endDate
				this.refreshOrderData()
			},

			// 上拉加载更多
			upCallback({
				num,
				size
			}) {
				const sign = this.currentTab.sign
				apiOrderList({
					type: sign,
					time_type: this.time.value,
					start_time: this.timeRange.start,
					end_time: this.timeRange.end,
					page_no: num,
					page_size: size,
					clsp_id: Cache.get('clsp_id'),
				}).then(({
					lists,
					page_size,
					count,
					extend
				}) => {
					const tab = this.mapTabsItem(sign)
					lists.forEach(item => item['buttons'] = this.getOrderStatusButtons(item.btn) ?? [])
					if (num === 1) tab.list = []
					tab.list = [...tab.list, ...lists]
					tab.list = this.$zhTran(tab.list)
					this.price_symbol = extend.price_symbol
					this.order_extend = extend
					this.mescroll.endSuccess(lists.length, count)
				}).catch(err => {
					this.mescroll.endErr()
				})
			},

			// 去订单详情
			goOrderDetail(id) {
				this.$Router.push({
					path: '/bundle2/pages/order_detail/order_detail',
					query: {
						order_id: id
					}
				})
			},
		},

		onLoad() {
			const options = this.$Route.query
			const mode = options.mode ?? 'all'
			const tabIndex = this.tabsList.findIndex(item => item['sign'] === mode)

			this.changeCurrentTab(tabIndex)
			setTimeout(() => {}, 0.5 * 1000)

			// 监听全局duringPayment事件
			uni.$on('duringPayment', ({
				result
			}) => {
				if (result === PaymentStatusEnum['SUCCESS']) {
					this.$Router.back()
					setTimeout(() => {
						this.$toast({
							title: this.$zhTran('支付成功')
						})
					}, 0.5 * 1000)
					this.refreshOrderData()
				}
			})
		},
		onUnload() {
			uni.$off('duringPayment')
		},
	}
</script>


<style lang="scss">
	page {
		height: 100%;
		padding: 0;
	}

	.order-list {
		height: 100%;
		display: flex;
		flex-direction: column;

		.order-item {
			flex: 1;
			min-height: 0;

			.order-item-box {
				height: calc(100% - 80rpx - constant(safe-area-inset-bottom));
				height: calc(100% - 80rpx - env(safe-area-inset-bottom));
			}
		}
	}

	.order-contain {
		padding: 0 20rpx;
	}

	.order {
		padding-left: 20rpx;
		margin-top: 20rpx;
		border-radius: 5px;
		background-color: #FFFFFF;

		&-header {
			// display: flex;
			height: 80rpx;
			align-items: center;
			padding-right: 20rpx;
			border-bottom: $-solid-border;

			.order-tag {
				padding: 4rpx 10rpx;
				margin-right: 10rpx;
				border-radius: 2px;
				font-size: $-font-size-xxs;
				color: #FFFFFF;

				&--pink {
					background: linear-gradient(#ff369a 0%, #ff2c3c 100%);
				}

				&--red {
					background: linear-gradient(#f95f2f 0%, #ff2c3c 100%);
				}

				&--blue {
					background: linear-gradient(#fa6aa9 0%, #fc00bb 100%);
				}

				&--green {
					background: linear-gradient(#0cc21e 0%, #06c160 100%);
				}
			}

			.order-sn {
				font-size: $-font-size-nr;
			}

			.order-status {
				margin-left: auto;
				font-size: $-font-size-sm;

				&--primary {
					@include font_color()
				}

				&--muted {
					color: $-color-muted;
				}
			}
		}

		&-main {
			.order-desc {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 20rpx;
				font-size: $-font-size-xs;
				color: $-color-muted;
			}
		}

		&-footer {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100rpx;
			padding-right: 20rpx;
			border-top: $-solid-border;

			.order-button {
				box-sizing: border-box;
				padding: 10rpx 30rpx;
				border-radius: 60px;
				font-size: $-font-size-nr;

				&:nth-child(n+2) {
					margin-left: 20rpx;
				}

				&--primary {
					@include background_color() color: #FFFFFF;
				}

				&--normal {
					border-width: 1px;
					border-style: solid;
					@include border_color() @include font_color()
				}

				&--muted {
					border: $-solid-border;
					color: $-color-lighter;
				}
			}
		}

	}

	.gfa-tag {
		width: 80rpx;
		height: 40rpx;
		border: 1rpx solid red;
		border-radius: 6rpx;
		color: red;
		display: flex;
		align-items: center;
		justify-content: center;
	}


	.query {

		&-line {
			padding: 20rpx 40rpx;
			margin: 20rpx 20rpx 0 20rpx;
			border-radius: 5px;
			background-color: #FFFFFF;

			.title {
				color: rgba(56, 56, 56, 1);
				font-size: 32rpx;
				font-weight: bold;
			}

			.line {
				height: 5rpx;
				width: 30rpx;
				background-color: rgba(166, 166, 166, 1);
			}

			.date {
				border: 1rpx solid rgba(243, 243, 243, 1);
				width: calc((100% - 70rpx) / 2);
				text-align: center;
				padding: 20rpx;
			}
		}
	}

	.time {

		&-header {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100rpx;
			padding: 0 30rpx;
			font-weight: bold;
			font-size: 32rpx;
			background-color: #FFFFFF;
		}

		&-main {
			padding: 0 30rpx 30rpx 30rpx;

			.time-sel {
				color: rgba(56, 56, 56, 1);
				background-color: rgba(246, 247, 249, 1);
				font-size: 28rpx;
				padding: 30rpx;
				text-align: center;
				margin-bottom: 15rpx;

				&.selected {
					color: #fff;
					@include background_color()
				}
			}
		}

		&-footer {
			padding: 0 20rpx env(safe-area-inset-bottom);
			padding-top: 20rpx;
			padding-bottom: 20rpx;
			background-color: #fff;

			.btn {
				flex: 1;

				&--cancel {
					color: rgba(38, 38, 38, 1);
				}
			}
		}
	}
</style>